<template>
  <div class="registered">
    <div class="registered-in">
      <div class="r-left">
        <p>{{ $t('login.tips') }}</p>
      </div>
      <div v-if="type === 'login'" class="r-right">
        <div class="r-top">
          <span class="ft-30">{{ $t('login.loginin') }}</span>
          <span class="grey" @click="handleChangeType('registered')">{{
            $t('login.registered')
          }}</span>
        </div>
        <div class="navbar">
          <div class="navbar-in active">1.{{ $t('login.inputEmail') }}</div>
        </div>
        <div class="navbar-box">
          <el-form ref="form" :model="form" :rules="loginRules" label-position="top">
            <el-form-item label="" prop="username">
              <el-input
                v-model="form.username"
                prefix-icon="el-icon-message"
                :placeholder="$t('login.userId')"
              ></el-input>
              <span class="grey">{{ $t('login.id') }}</span>
            </el-form-item>
            <el-form-item label="" prop="password">
              <el-input
                v-model="form.password"
                type="password"
                prefix-icon="el-icon-lock"
                :placeholder="$t('login.password')"
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="ft-16">
            <span>
              {{ $t('login.forgetPwd') }}?
              <em class="blue" @click="handleChangeType('resetPassword')">
                {{ $t('login.resetPwd') }}
              </em>
            </span>
          </div>
          <div class="ft-16">
            <el-button class="submit" @click="login">{{ $t('common.submit') }}</el-button>
            <span>
              {{ $t('login.noLogin') }}？
              <em class="blue" @click="handleChangeType('registered')">
                {{ $t('login.registered') }}
              </em>
            </span>
          </div>
        </div>
      </div>
      <div v-if="type === 'registered'" class="r-right">
        <div class="r-top">
          <span class="ft-30">{{ $t('login.registered') }}</span>
          <span class="grey" @click="handleChangeType('login')">{{ $t('login.loginin') }}</span>
        </div>
        <div v class="navbar">
          <div
            v-for="(item, index) in tabs"
            :key="index"
            class="navbar-in"
            :class="{ active: active === index }"
          >
            {{ index + 1 }}.{{ item[lang] }}
          </div>
        </div>
        <div v-if="active === 0" class="navbar-box">
          <el-form ref="form0" :model="form" :rules="rules" label-position="top">
            <el-form-item prop="email" label="">
              <el-input
                v-model="form.email"
                prefix-icon="el-icon-message"
                :placeholder="$t('login.emailAdress')"
              ></el-input>
            </el-form-item>
            <el-form-item prop="repeatEmail" label="">
              <el-input
                v-model="form.repeatEmail"
                prefix-icon="el-icon-lock"
                :placeholder="$t('login.confirmAdress')"
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="ft-16">
            <el-button :loading="loading" class="submit" @click="handleSure">
              {{ $t('common.next') }}
            </el-button>
            <span>
              {{ $t('login.hasLogin') }}？<em class="blue" @click="handleChangeType('login')">{{
                $t('login.loginin')
              }}</em>
            </span>
          </div>
        </div>
        <div v-if="active === 1" class="navbar-box">
          <el-form ref="form1" :model="form" :rules="rules" label-position="top">
            <el-form-item prop="code" label="">
              <el-input
                v-model="form.code"
                prefix-icon="el-icon-message"
                :placeholder="$t('login.inputCode')"
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="ft-16">
            <el-button :loading="loading" class="submit" @click="handleSure">
              {{ $t('common.next') }}
            </el-button>
            <span>
              {{ $t('login.hasLogin') }}？<em class="blue" @click="handleChangeType('login')">{{
                $t('login.loginin')
              }}</em>
            </span>
          </div>
        </div>
        <div v-if="active === 2" class="navbar-box">
          <el-form ref="form2" :model="form" :rules="rules" label-position="top">
            <el-form-item prop="nickname" label="">
              <el-input
                v-model="form.nickname"
                prefix-icon="el-icon-user"
                :placeholder="$t('login.inputNickname')"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password" label="">
              <el-input
                v-model="form.password"
                type="password"
                prefix-icon="el-icon-lock"
                :placeholder="$t('login.inputPassword')"
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="ft-16">
            <el-button :loading="loading" class="submit" @click="handleSure">
              {{ $t('common.next') }}
            </el-button>
            <span>
              {{ $t('login.hasLogin') }}？<em class="blue" @click="handleChangeType('login')">{{
                $t('login.loginin')
              }}</em>
            </span>
          </div>
        </div>
        <div v-if="active === 3" class="navbar-box info">
          <div>
            <div class="gender" @click="changeGender">
              <div class="gender-in" :class="{ active: form.sex }">
                <span>{{ $t('common.form.mr') }}</span>
                <em></em>
              </div>
              <div class="gender-in" :class="{ active: !form.sex }">
                <span>{{ $t('common.form.ms') }}</span>
                <em></em>
              </div>
            </div>
            <el-form ref="form3" :model="form" :rules="rules" label-position="top">
              <el-form-item prop="name" label="">
                <el-input v-model="form.name" :placeholder="$t('login.inputName')"></el-input>
              </el-form-item>
              <el-form-item prop="company" label="">
                <el-input v-model="form.company" :placeholder="$t('login.inputCompany')"></el-input>
              </el-form-item>
              <el-form-item prop="verticalMarket" label="">
                <el-input
                  v-model="form.verticalMarket"
                  :placeholder="$t('login.inputVerticalMarket')"
                ></el-input>
              </el-form-item>
              <el-form-item prop="phone" label="">
                <el-input v-model="form.phone" :placeholder="$t('login.inputPhone')"></el-input>
              </el-form-item>
              <el-form-item prop="area" label="">
                <el-input v-model="form.area" :placeholder="$t('login.inputRegion')"></el-input>
              </el-form-item>
              <el-form-item prop="howFind" label="">
                <el-input v-model="form.howFind" :placeholder="$t('login.inputHowFind')"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="ft-16">
            <el-button :loading="loading" class="submit" @click="handleSure">
              {{ $t('common.submit') }}
            </el-button>
            <span>
              {{ $t('login.hasLogin') }}？<em class="blue" @click="handleChangeType('login')">{{
                $t('login.loginin')
              }}</em>
            </span>
          </div>
        </div>
      </div>
      <div v-if="type === 'resetPassword'" class="r-right">
        <div class="r-top">
          <span class="ft-30">{{ $t('login.resetPwd') }}</span>
          <span class="grey" @click="handleChangeType('registered')">{{
            $t('login.registered')
          }}</span>
        </div>
        <div v class="navbar">
          <div
            v-for="(item, index) in restTabs"
            :key="index"
            class="navbar-in"
            :class="{ active: active === index }"
          >
            {{ index + 1 }}.{{ item[lang] }}
          </div>
        </div>
        <div v-if="active === 0" class="navbar-box">
          <el-form ref="formReset0" :model="form" :rules="rules" label-position="top">
            <el-form-item prop="email" label="">
              <el-input
                v-model="form.email"
                prefix-icon="el-icon-message"
                :placeholder="$t('login.emailAdress')"
              ></el-input>
            </el-form-item>
            <el-form-item prop="repeatEmail" label="">
              <el-input
                v-model="form.repeatEmail"
                prefix-icon="el-icon-lock"
                :placeholder="$t('login.confirmAdress')"
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="ft-16">
            <el-button :loading="loading" class="submit" @click="handleSure">
              {{ $t('common.next') }}
            </el-button>
            <span>
              {{ $t('login.hasLogin') }}？<em class="blue" @click="handleChangeType('login')">{{
                $t('login.loginin')
              }}</em>
            </span>
          </div>
        </div>
        <div v-if="active === 1" class="navbar-box">
          <el-form ref="formReset1" :model="form" :rules="rules" label-position="top">
            <el-form-item prop="code" label="">
              <el-input
                v-model="form.code"
                prefix-icon="el-icon-message"
                :placeholder="$t('login.inputCode')"
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="ft-16">
            <el-button :loading="loading" class="submit" @click="handleSure">
              {{ $t('common.next') }}
            </el-button>
            <span>
              {{ $t('login.hasLogin') }}？<em class="blue" @click="handleChangeType('login')">{{
                $t('login.loginin')
              }}</em>
            </span>
          </div>
        </div>
        <div v-if="active === 2" class="navbar-box">
          <el-form ref="formReset2" :model="form" :rules="rules" label-position="top">
            <el-form-item prop="password" label="">
              <el-input
                v-model="form.password"
                prefix-icon="el-icon-lock"
                :placeholder="$t('login.inputNewPassword')"
              ></el-input>
            </el-form-item>
            <el-form-item prop="repeatPassword" label="">
              <el-input
                v-model="form.repeatPassword"
                prefix-icon="el-icon-lock"
                :placeholder="$t('login.confirmPassword')"
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="ft-16">
            <el-button :loading="loading" class="submit" @click="handleSure">
              {{ $t('common.submit') }}
            </el-button>
            <span>
              {{ $t('login.hasLogin') }}？<em class="blue" @click="handleChangeType('login')">{{
                $t('login.loginin')
              }}</em>
            </span>
          </div>
        </div>
      </div>
      <div class="close">
        <i class="el-icon-circle-close" @click="close"></i>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { email } from '@/utils/validator'
import * as api from '@/const/api'

export default {
  props: {
    defaultType: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      type: '', // type: registered | login | resetPassword
      form: {
        email: '',
        repeatEmail: '',
        code: '',
        nickname: '',
        password: '',
        repeatPassword: '',
        sex: true,
        name: '',
        company: '',
        verticalMarket: '',
        phone: '',
        area: '',
        howFind: '',
      },
      tabs: [
        {
          en: 'Enter Your Email Address',
          zh: '输入您的邮件地址',
        },
        {
          en: 'Verify Your Email Address',
          zh: '验证您的电子邮件地址',
        },
        {
          en: 'Enter Your Information',
          zh: '输入您的信息',
        },
        {
          en: 'Enter Application Information',
          zh: '输入申请信息',
        },
      ],
      restTabs: [
        {
          en: 'Enter Your Email Address',
          zh: '输入您的邮件地址',
        },
        {
          en: 'Verify Your Email Address',
          zh: '验证您的电子邮件地址',
        },
        {
          en: 'Enter A New Password',
          zh: '输入新的密码',
        },
      ],
      loginRules: {
        username: [
          {
            required: true,
            message: `${this.$t('common.input')}${this.$t('login.userId')}`,
            trigger: 'change',
          },
        ],
        password: [{ required: true, message: this.$t('login.inputPassword'), trigger: 'change' }],
      },
      active: 0,
      loading: false,
    }
  },
  computed: {
    ...mapState(['lang']),
    rules() {
      const rulesMap = {
        0: {
          email: [
            { required: true, message: this.$t('login.inputEmail'), trigger: 'change' },
            {
              pattern: email,
              message: this.$t('login.inputValidEmail'),
              trigger: 'blur',
            },
          ],
          repeatEmail: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  return callback(new Error(this.$t('login.confirmAdress')))
                }

                if (value === this.form.email) {
                  callback()
                } else {
                  return callback(new Error(this.$t('login.reEnterAdress')))
                }
              },
              trigger: 'blur',
            },
          ],
        },
        1: {
          code: [{ required: true, message: this.$t('login.inputCode'), trigger: 'change' }],
        },
        2: {
          nickname: [
            { required: true, message: this.$t('login.inputNickname'), trigger: 'change' },
          ],
          password: [
            { required: true, message: this.$t('login.inputPassword'), trigger: 'change' },
          ],
          repeatPassword: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  return callback(new Error(this.$t('login.confirmPassword')))
                }

                if (value === this.form.password) {
                  callback()
                } else {
                  return callback(new Error(this.$t('login.reEnterPassword')))
                }
              },
              trigger: 'change',
            },
          ],
        },
        3: {
          name: [{ required: true, message: this.$t('login.inputName'), trigger: 'change' }],
          company: [{ required: true, message: this.$t('login.inputCompany'), trigger: 'change' }],
          verticalMarket: [
            { required: true, message: this.$t('login.inputVerticalMarket'), trigger: 'change' },
          ],
          phone: [{ required: true, message: this.$t('login.inputPhone'), trigger: 'change' }],
          area: [{ required: true, message: this.$t('login.inputRegion'), trigger: 'change' }],
          howFind: [{ required: true, message: this.$t('login.inputHowFind'), trigger: 'change' }],
        },
      }
      return rulesMap[this.active]
    },
  },
  mounted() {
    this.type = this.defaultType
  },
  methods: {
    async handleChangeType(type) {
      this.type = type
      this.active = 0

      await this.$nextTick()

      this.$refs.formReset0 && this.$refs.formReset0.clearValidate()
      this.$refs.form0 && this.$refs.form0.clearValidate()
      this.$refs.form && this.$refs.form.clearValidate()
    },
    async handleSure() {
      try {
        if (this.active === 0) {
          if (this.type === 'resetPassword') {
            await this.$refs[`formReset${this.active}`].validate()
          } else {
            await this.$refs[`form${this.active}`].validate()
          }

          this.loading = true
          const { code, msg } = await this.$axios.$post(api.mailSend, {
            email: this.form.email,
            lang: this.lang, // zh 或 en
          })
          if (+code !== 200) {
            throw new Error(msg || this.$t('common.form.error'))
          }
        }

        if (this.active === 1) {
          if (this.type === 'resetPassword') {
            await this.$refs[`formReset${this.active}`].validate()
          } else {
            await this.$refs[`form${this.active}`].validate()
          }
          this.loading = true
          const { code, msg } = await this.$axios.$post(api.mailValid, {
            email: this.form.email,
            code: this.form.code, // zh 或 en
          })
          if (+code !== 200) {
            throw new Error(msg || this.$t('common.form.error'))
          }
        }

        if (this.active === 2) {
          if (this.type === 'resetPassword') {
            await this.$refs[`formReset${this.active}`].validate()

            const { code, msg } = await this.$axios.$post(api.userModifyPassword, {
              username: this.form.email,
              password: this.form.password,
            })
            if (+code !== 200) {
              throw new Error(msg || this.$t('common.form.error'))
            }

            this.$message.success(this.$t('common.form.success'))
            this.close()
          } else {
            await this.$refs[`form${this.active}`].validate()
          }
        }

        if (this.active === 3) {
          await this.$refs[`form${this.active}`].validate()

          this.loading = true

          const {
            email,
            password,
            area,
            company,
            howFind,
            verticalMarket,
            name,
            nickname,
            phone,
            sex,
          } = this.form
          const params = {
            username: email,
            password,
            accountEmail: email,
            area,
            company,
            howFind,
            name,
            nickname,
            phone,
            verticalMarket,
            sex: sex ? 1 : 0,
          }

          const { code, msg } = await this.$axios.$post(api.userRegister, params)
          if (+code !== 200) {
            throw new Error(msg || this.$t('common.form.error'))
          }

          this.$message.success(this.$t('common.form.success'))
          this.close()
        }

        this.active++
      } catch (err) {
        err.message && this.$message.error(err.message)
      } finally {
        this.loading = false
      }
    },
    async login() {
      try {
        await this.$refs.form.validate()
        const params = {
          username: this.form.username,
          password: this.form.password,
        }
        const { code, msg, data } = await this.$axios.$post(api.userLogin, params)

        if (+code !== 200) {
          throw new Error(msg || this.$t('common.form.error'))
        }
        this.$store.commit('update', {
          token: data.token,
          userInfo: data.userInfo,
        })
        this.$message.success(this.$t('login.loginSuccess'))
        this.$cookies.set('userInfo', data.userInfo)
        this.close()
      } catch (err) {
        err.message && this.$message.error(err.message)
      } finally {
        this.loading = false
      }
    },
    changeGender() {
      this.$set(this.form, 'sex', !this.form.sex)
    },
    close() {
      this.$emit('hide')
    },
  },
}
</script>

<style lang="less" scoped>
@import '~assets/var';

.registered {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.7);
  position: fixed;
  z-index: 99;

  .registered-in {
    background-image: url(@/assets/images/registered-bg.png);
    background-size: 100% 100%;
    .width(1400);
    .height(580);
    .mg(260, 260, 0, 260);

    display: flex;
    position: relative;

    .r-left {
      .width(450);
      .pd(400, 0, 0, 160);

      p {
        .ft(14);
        .lineH(24);

        font-weight: 500;
        color: #fff;
      }
    }

    .r-right {
      flex: 1;
      .ft(16);
      .pd(80, 180, 0, 72);

      .r-top {
        display: flex;
        justify-content: space-between;
        align-items: center;

        span {
          cursor: pointer;
        }
      }

      .navbar {
        .pd(20, 0, 0, 0);

        display: flex;
        border-bottom: 1px solid #e5e5e5;

        .navbar-in {
          position: relative;
          .ft(15);
          .lineH(20);
          .pd(10, 30, 10, 0);

          &.active {
            color: #0762cb;

            &::after {
              position: absolute;
              bottom: 0;
              content: '';
              display: block;
              .width(100);
              .height(2);

              background: #0762cb;
            }
          }
        }
      }

      .navbar-box {
        .el-form {
          .pd(40, 0, 0, 0);

          .el-form-item {
            .mg(0, 0, 24, 0);
          }

          .el-input {
            .width(370);
            .mg(0, 10, 0, 0);
          }

          :deep(.el-form-item__content) {
            .lineH(48);
          }

          :deep(.el-input__inner) {
            .height(48);
            .lineH(48);
            .ft(18);
          }

          span {
            .ft(16);
          }
        }

        &.info {
          .gender {
            .ft(14);
            .mg(12, 0, 12, 0);

            display: flex;

            .gender-in {
              display: flex;
              align-items: center;
              cursor: pointer;

              &.active {
                span {
                  color: #075fc4;
                }

                em {
                  background-image: url(@/assets/images/index/selected-active.png);
                }
              }

              em {
                display: inline-block;
                .width(20);
                .height(20);

                background-image: url(@/assets/images/index/selected.png);
                background-size: 100% 100%;
                .mg(0, 20, 0, 4);
              }

              span {
                .mg(0, 0, 0, 0);
              }
            }
          }

          .el-form {
            padding: 0;

            .el-form-item {
              width: 47%;
              display: inline-block;
              .mg(0, 0, 20, 0);

              &:nth-child(2n) {
                margin-left: 2%;
              }

              .el-input {
                width: 100%;
              }

              :deep(.el-input__inner) {
                .height(48);
                .lineH(48);
              }

              :deep(.el-form-item__error) {
                .ft(14);
                .pd(4, 0, 0, 0);
              }
            }
          }

          .submit {
            .mg(4, 20, 0, 0);
          }
        }
      }

      .submit {
        .width(370);
        .height(54);
        .mg(40, 20, 0, 0);

        color: #fff;
        border: none;
        background: linear-gradient(90deg, #549aea, #0762cb);
        box-shadow: 0 7px 27px 0 rgba(7, 98, 203, 0.51);
        border-radius: 27px;
      }
    }

    .ft-30 {
      .ft(30);

      color: #0762cb;
      font-weight: bold;
    }

    .ft-16 {
      .ft(16);

      color: #666;
    }

    em {
      font-style: normal;
      cursor: pointer;
    }

    .grey {
      color: #999;
    }
  }

  .close {
    .width(30);
    .height(30);
    .ft(30);
    .mg(0, 150, 0, 0);

    color: #fff;
    right: 0;
    position: absolute;
    cursor: pointer;
  }
}
</style>
